package com.peter.api.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.peter.api.annotation.AuthCheck;
import com.peter.api.common.BaseResponse;
import com.peter.api.common.DeleteRequest;
import com.peter.api.common.ErrorCode;
import com.peter.api.common.ResultUtils;
import com.peter.api.constant.UserConstant;
import com.peter.api.exception.BusinessException;
import com.peter.api.exception.ThrowUtils;

import com.peter.api.model.dto.interfaceInfoDTO.InterfaceInfoAddRequest;
import com.peter.api.model.dto.interfaceInfoDTO.InterfaceInfoEditRequest;
import com.peter.api.model.dto.interfaceInfoDTO.InterfaceInfoQueryRequest;
import com.peter.api.model.dto.post.PostQueryRequest;
import com.peter.api.model.entity.InterfaceInfo;
import com.peter.api.model.entity.Post;
import com.peter.api.model.entity.User;

import com.peter.api.model.vo.InterfaceInfoVO;
import com.peter.api.service.InterfaceInfoService;
import com.peter.api.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/interface")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        //实体
        Map<String, Consumer<String>> setters = new HashMap<>();
        setters.put("name", interfaceInfo::setName);
        setters.put("description", interfaceInfo::setDescription);
        setters.put("url", interfaceInfo::setUrl);
        setters.put("requestHeader", interfaceInfo::setRequestHeader);
        setters.put("responseHeader", interfaceInfo::setResponseHeader);
        setters.put("method", interfaceInfo::setMethod);
        //dto
        Map<String, String> values = new HashMap<>();
        values.put("name", interfaceInfoAddRequest.getName());
        values.put("description", interfaceInfoAddRequest.getDescription());
        values.put("url", interfaceInfoAddRequest.getUrl());
        values.put("requestHeader", interfaceInfoAddRequest.getRequestHeader());
        values.put("responseHeader", interfaceInfoAddRequest.getResponseHeader());
        values.put("method", interfaceInfoAddRequest.getMethod());

        values.forEach((key, value) -> {
            if (value != null) {
                setters.get(key).accept(value);
            }
        });


        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        interfaceInfo.setStatus(0);

        boolean result = interfaceInfoService.save(interfaceInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param postUpdateRequest
     * @return
     */
//    @PostMapping("/update")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest postUpdateRequest) {
//        if (postUpdateRequest == null || postUpdateRequest.getId() <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        InterfaceInfo post = new InterfaceInfo();
//        BeanUtils.copyProperties(postUpdateRequest, post);
//        List<String> tags = postUpdateRequest.getTags();
//        if (tags != null) {
//            post.setTags(JSONUtil.toJsonStr(tags));
//        }
//        // 参数校验
//        postService.validInterfaceInfo(post, false);
//        long id = postUpdateRequest.getId();
//        // 判断是否存在
//        InterfaceInfo oldInterfaceInfo = postService.getById(id);
//        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
//        boolean result = postService.updateById(post);
//        return ResultUtils.success(result);
//    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<InterfaceInfoVO> getInterfaceInfoVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo post = interfaceInfoService.getById(id);
        if (post == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(interfaceInfoService.getInterfaceInfoVO(post, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(@RequestBody InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        Page<InterfaceInfo> postPage = interfaceInfoService.page(new Page<>(current, size),
                interfaceInfoService.getQueryWrapper(interfaceInfoQueryRequest));
        return ResultUtils.success(postPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<InterfaceInfoVO>> listInterfaceInfoVOByPage(@RequestBody InterfaceInfoQueryRequest postQueryRequest,
            HttpServletRequest request) {
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<InterfaceInfo> postPage = interfaceInfoService.page(new Page<>(current, size),
                interfaceInfoService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(interfaceInfoService.getInterfaceInfoVOPage(postPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
//    @PostMapping("/my/list/page/vo")
//    public BaseResponse<Page<InterfaceInfoVO>> listMyInterfaceInfoVOByPage(@RequestBody InterfaceInfoQueryRequest postQueryRequest,
//            HttpServletRequest request) {
//        if (postQueryRequest == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User loginUser = userService.getLoginUser(request);
//        postQueryRequest.setUserId(loginUser.getId());
//        long current = postQueryRequest.getCurrent();
//        long size = postQueryRequest.getPageSize();
//        // 限制爬虫
//        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
//        Page<InterfaceInfo> postPage = postService.page(new Page<>(current, size),
//                postService.getQueryWrapper(postQueryRequest));
//        return ResultUtils.success(postService.getInterfaceInfoVOPage(postPage, request));
//    }

    // endregion

    /**
     * 分页搜索（从 ES 查询，封装类）
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
//    @PostMapping("/search/page/vo")
//    public BaseResponse<Page<InterfaceInfoVO>> searchInterfaceInfoVOByPage(@RequestBody InterfaceInfoQueryRequest postQueryRequest,
//            HttpServletRequest request) {
//        long size = postQueryRequest.getPageSize();
//        // 限制爬虫
//        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
//        Page<InterfaceInfo> postPage = postService.searchFromEs(postQueryRequest);
//        return ResultUtils.success(postService.getInterfaceInfoVOPage(postPage, request));
//    }

    /**
     * 编辑（用户）
     *
     * @param interfaceInfoEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editInterfaceInfo(@RequestBody InterfaceInfoEditRequest interfaceInfoEditRequest, HttpServletRequest request) {
        if (interfaceInfoEditRequest == null || interfaceInfoEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoEditRequest, interfaceInfo);
        Map<String, Consumer<String>> setters = new HashMap<>();
        setters.put("name", interfaceInfo::setName);
        setters.put("description", interfaceInfo::setDescription);
        setters.put("url", interfaceInfo::setUrl);
        setters.put("requestHeader", interfaceInfo::setRequestHeader);
        setters.put("responseHeader", interfaceInfo::setResponseHeader);
        setters.put("method", interfaceInfo::setMethod);

        Map<String, String> values = new HashMap<>();
        values.put("name", interfaceInfoEditRequest.getName());
        values.put("description", interfaceInfoEditRequest.getDescription());
        values.put("url", interfaceInfoEditRequest.getUrl());
        values.put("requestHeader", interfaceInfoEditRequest.getRequestHeader());
        values.put("responseHeader", interfaceInfoEditRequest.getResponseHeader());
        values.put("method", interfaceInfoEditRequest.getMethod());

        values.forEach((key, value) -> {
            if (value != null) {
                setters.get(key).accept(value);
            }
        });

        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        User loginUser = userService.getLoginUser(request);
        long id = interfaceInfoEditRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldInterfaceInfo.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

}
